<?php
namespace App\Logics;

use App\Models\ChannelModel;
use App\Models\CouCouponModel;
use App\Models\HbDjModel;
use App\Models\LogNotifyAlipayModel;
use App\Models\LogXxhfModel;
use App\Models\OrderOperatorModel;
use App\Models\OrderStagesModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\OrderModel;
use App\Models\OrderGroupModel;
use App\Models\OrderGroupBinModel;
use App\Models\UserModel;

use Encore\Admin\Facades\Admin;
use App\Libs\Common\ZmXyController;
use App\Libs\Common\ZhimaController;
use App\Libs\Common\JdDkController;
use App\Libs\Common\SignatureController;
use App\Libs\Common\AlFundController;

use App\Libs\Vendor\AliPaySdk\aop\AopClient;
use App\Libs\Vendor\AliPaySdk\aop\request\AlipaySecurityRiskCustomerriskQueryRequest;


use App\Libs\Common\CsvUtil;


//逻辑处理
class OrderLogic extends BaseLogic {


    public function __construct()
    {
        parent::__construct();

    }

    /**
     * @param array $para
     * @return array
     */
    public  function getOrderList(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_type=isset($para['order_type'])?$para['order_type']:0;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';
        $group_id = isset($para['group_id'])?$para['group_id']:0;
        $status = isset($para['status'])?$para['status']:-1;

        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status!=-1 ){
            if($status ==-1)$where['order_status'] = $order_status;

            $searchWhere[] = ['order_status',$order_status];
            if($status==3){
                $searchWhere[] = ['express','<>',''];
                $searchWhere[] = ['exp_number','<>',''];
            }
            if($status==33){
                $searchWhere[] = ['express',''];
                $searchWhere[] = ['exp_number',''];
                $searchWhere[] = ['order_delivery_time','<>',''];
            }
        }
        if($status==100){
            $searchWhere[] = ['exp_number',''];
        }

        if($order_type){
            $where['order_type'] = $order_type;
            $searchWhere[] = ['order_type',$order_type];
        }
        if($order_comefrom){
            $where['order_comefrom'] = $order_comefrom;
            $searchWhere[] = ['order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['order_id', 'like', $order_id . '%'];
        }
        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $where['user_phone'] = $user_phone;
            $searchWhere[] = ['user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $where['user_name'] = $user_name;
            $searchWhere[] = ['user_name', 'like', $user_name . '%'];
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="`order_create_time` > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="`order_create_time` <  ? ";
            $whereCol[]=$end_time;
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }
        if($group_id>0){
            $where['group_id']=$group_id;
            $order_ids=OrderLogic::getOrderIdsByGroupId($group_id)?:[0];
        }


        $model = OrderModel::where($searchWhere);
        if($group_id>0 && $order_ids) $model->whereIn('order_id',$order_ids);

        if($status==100)$model->whereIn('order_status',[3,4,5,8]);
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $order_ids=$data['data']?array_column($data['data'],'order_id'):[0];
        $xxhf=LogXxhfLogic::getResByOrderIds($order_ids);
        $channel=ChannelLogic::pluck('cha_describe','cha_name');
        $url=config('sys.img_url').'/';
        $order_status=config('sys.order_status');

        $groups=OrderLogic::getGroupNameByOrderIds($order_ids);
        foreach($data['data'] as $k=>$v){
            $data['data'][$k]["goods_order_thumbnail"]=$url.trim($v['goods_order_thumbnail'],'/');
            $data['data'][$k]["order_address"]=$v["user_province"].$v["user_address"];
            $data['data'][$k]["order_comefrom"]=$channel[$v['order_comefrom']]??'';//订单来源
            $data['data'][$k]['log_xxhf']=$xxhf[$v['order_id']]??'';
            $data['data'][$k]['order_status']=$order_status[$v['order_status']]??'';
            if($status==33){
                $data['data'][$k]['order_status']='已出库';
            }
            $data['data'][$k]['group_name']=$groups[$v['order_id']]??[];
        }


        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url='?';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);


        $order_group=OrderGroupLogic::pluck('name','id');
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'channel'=>$channel,
            'excel_url'=>$excel_url,
            'order_group'=>$order_group
        ];
        return $arr;
    }

    public static function getOrder(array $where,array $fields=['brand_id','brand_name']){

        $data=OrderModel::where($where)->select($fields)->get();
        return ob_to_array($data);
    }

    //获取一个
    public static function  getOne($id,$fields=['*']){
        $id=(int)$id;
        $data= OrderModel::where('id',$id)->select($fields)->first();
        return ob_to_array($data);
    }

    public static function getOneByOrderId($order_id,$fields=['*']){
        $order_id=trim($order_id);
        $data= OrderModel::where('order_id',$order_id)->select($fields)->first();
        return ob_to_array($data);
    }


    //判断该数据是否存在
    public static function isOne($id){
        $id=(int)$id;
        return OrderModel::where('id',$id)->count();
    }

    //判断该数据是否存在
    public static function isOneByOrderId($order_id){
        $order_id=trim($order_id);
        return OrderModel::where('order_id',$order_id)->count();
    }

    //根据订单id获取对应的分组名
    public static function getGroupNameByOrderIds(array $order_ids){
        $group=OrderGroupBinModel::join('order_group as g',"g.id","=","order_group_bin.group_id")
            ->whereIn('order_group_bin.order_id',$order_ids)->select("g.name",'order_group_bin.order_id')->get();
        $group=ob_to_array($group);
        $groups=[];
        foreach ($group as $k=>$v){
            $groups[$v['order_id']][]=$v['name'];
        }
        return $groups;
    }

    //根据分组名获取对应的订单id
    public static function getOrderIdsByGroupId(int $group_id){
        $group_id=(int)$group_id;
        $data= OrderGroupBinModel::where('group_id',$group_id)->pluck('order_id');
        return ob_to_array($data);
    }


    //还款时间转换 生成分期时间 $day,$month
    public static function hk_date($day,int $month,int $day_num){
        $data=date('Y-m-d',strtotime("$day+5 day"));

        if ($month == 1) {
            return date("Y-m-d H:i:s",strtotime(substr($data,0,10)));
        }else{
            $yue=($month-1) * $day_num;

            $month=date('Y-m-d',strtotime("$data+$yue day"));
            return date("Y-m-d H:i:s",strtotime(substr($month,0,10)));
        }
    }

    //订单生效时间+5天
    public static function order_sxsj($mon='')
    {
        $day=date('Y-m-d H:i:s',time());
        $data=date('Y-m-d H:i:s',strtotime("$day+5 day"));
        if ($mon != '')
        {
            $data=date('Y-m-d H:i:s',strtotime("$data+$mon month"));
        }
        return $data;
    }

    /**
     *  取消订单、拒绝订单时调用
     *  $order_id 订单号
     *  $my_cou_id 我的优惠券表的ID
     */
    public static function cancelCoupon($order_id,$my_cou_id)
    {
        DB::beginTransaction();
        try{
            $res= CouCouponModel::where("id",$my_cou_id)->update(['my_cou_status'=>1]);
            if(empty($res)) throw new \Exception('失败');
            $res=OrderModel::where("order_id",$order_id)->update(['my_cou_id'=>0]);
            if(empty($res)) throw new \Exception('失败');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        return true;
    }

    /** 订单详情
     * @param $order_id
     * @return array|string
     */
    public  function getOrderInfo($order_id){
        $order_id=trim(request("order_id"));

        if(empty($order_id)) return '参数错误';

        $order=OrderModel::leftJoin("user as b",'orders.user_phone','=','b.phone')
            ->where("orders.order_id",$order_id)->first();
        if(empty($order))  return '参数错误';
        $order=ob_to_array($order);
        $row=LogNotifyAlipayLogic::getOne([['order_stages_id',$order['zm_order_no']]],['trade_status']);
        if(!$row)
        {
            $row["trade_status"]= '未付款';
        }else{
            if($row["trade_status"] == 'TRADE_SUCCESS')
            {
                $row["trade_status"]= '付款成功';
            }

            if($row["trade_status"] == 'TRADE_FINISHED')
            {
                $row["trade_status"]= '交易关闭';
            }
        }
        $order_ins=OrderStagesLogic::getListByOrderId($order_id);
        $order_oper=OrderOperatorLogic::getListByOrderId($order_id);
        $channel=ChannelLogic::pluck('cha_describe','cha_name');
        $order_status=config('sys.order_status');
        $order['order_status']=isset($order_status[$order['order_status']])?$order_status[$order['order_status']]:'错误状态';
        $order['order_from']=$channel[$order['order_comefrom']]??'未知来源';
        if($order['order_status']==3 && $order['exp_number']=='')$order['order_status']='已出库';
        $img_url=config('sys.img_url');
        $data=[
            'order'=>$order,
            'order_ins'=>$order_ins,
            'order_oper'=>$order_oper,
            'row'=>$row,
            'img_url'=>$img_url
        ];
        return $data;
    }

    public function orderStagesInfo(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        if(empty($order_id)) return '缺少订单id';


        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];
        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['o.order_id', 'like', $order_id . '%'];
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }



        $fields=['o.order_status','o.order_id','o.user_name','o.user_phone','o.order_comefrom','o.goods_name',
            'o.goods_price','o.order_tenancy_term','o.order_create_time',
            'order_stages.current_tenancy_term','order_stages.monthly_rent','order_stages.total_pay','order_stages.paid_monthly_rent','order_stages.repayment_time','order_stages.last_repayment_time',
            'order_stages.balance','order_stages.days_overdue','order_stages.amount_override','order_stages.order_goods_insurance','order_stages.goods_installation_charge','order_stages.cou_credit_amount',
            'order_stages.cou_onle_id','order_stages.fq_status','order_stages.alipay_fund_order_no','order_stages.order_stages_pay','order_stages.out_order_id','order_stages.create_time'
        ];
        $model=OrderStagesModel::join('orders as o','order_stages.order_id','=','o.order_id')
            ->where($searchWhere)->select($fields);
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);

        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);

        $fq_status=config('sys.fq_status');
        $order_stages_pay=config('sys.order_stages_pay');
        $order_status=config('sys.order_status');
        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['order_status']=isset($order_status[$v['order_status']])?$order_status[$v['order_status']]:'';
            $data['data'][$k]['fq_status']=isset($fq_status[$v['fq_status']])?$fq_status[$v['fq_status']]:'';
            $data['data'][$k]['order_stages_pay']=isset($order_stages_pay[$v['order_stages_pay']])?$order_stages_pay[$v['order_stages_pay']]:'';
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url="?";
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);

        $channel=ChannelModel::pluck('cha_describe','cha_name');
        $channel=ob_to_array($channel);
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'channel'=>$channel,
            'excel_url'=>$excel_url
        ];
        return $arr;
    }

    /**取消订单
     * @param $order_id
     * @return array
     */
    public  function quxiao($order_id){
        if(empty($order_id)) return error('缺少参数');
        $data=[
            'order_status'=>6,
            'order_remarks'=>'后台主动取消'
        ];
        $fields=["my_cou_id","order_id","zm_order_no","order_comefrom","order_status","order_type"];
        $row=OrderLogic::getOneByOrderId($order_id,$fields);
        if(empty($row)) return error('该订单不存在');

        if($row["order_type"] == 2)
        {
            $count= LogNotifyAlipayModel::where("order_stages_id",$row['zm_order_no'])->count();
        }


        if (!in_array($row["order_status"], [0,1,2]))return error('该订单不允许取消');
        if(!empty($row["zm_order_no"]))
        {
            if ($row["order_comefrom"] == 'H5_ZFB')
            {
                $ZmXy= new ZmXyController();
                $res=$orderRentCancel=$ZmXy->orderRentCancel($row['zm_order_no']);
                if (!$res)return error('信用借还订单取消失败');
            }

            if ($row["order_comefrom"] == 'H5_JD')
            {
                $JdDk=new JdDkController();
                $res=$JdDk->contractCancel($row['order_id'],$row['zm_order_no']);
                if (!$res)return error('代扣协议取消失败');
            }

            if(strpos($row["order_comefrom"],"XCX_ZFB") !== false)
            {
                $data["describe"]="等待异步结果";
                $OutApi=new ZhimaController();
                $res=$orderRentCancel=$OutApi->credit_pay('CANCEL',$row['order_id'],$row['zm_order_no']);

                if (!$res)return error('信用借还订单取消失败');
            }
        }

        // 支付宝花呗 取消
        if($row["order_comefrom"] == "H5_ZFB_HB")
        {
            if($row["order_type"] == 1)
            {
                $rw=HbDjModel::where("out_order_no",$row['order_id'])->selectRaw("auth_no,out_order_no,amount")->first();
                $rw=ob_to_array($rw);
                $AlFund=new AlFundController();
                $unfreeze_res=$AlFund->unfreeze($rw["auth_no"],$rw["out_order_no"],$rw["amount"]);

                if (!$unfreeze_res)return error('信用借还订单取消失败');
            }

            if($row["order_type"] == 2 && $count)
            {
                return error('已付款的订单不能取消');
            }
        }

        //如果有使用优惠券
        if (!empty($row["my_cou_id"]))
        {
            $res=OrderLogic::cancelCoupon($order_id,$row["my_cou_id"]);
            if (!$res)return error('更改优惠券状态失败');
        }

        $res= OrderModel::where("order_id",$order_id)->update($data);
        if($res) return success('订单取消成功');
        return error('订单取消失败');

    }


    /**审核订单
     * @param string $order_id
     * @param int $order_status
     * @param $remarks
     * @return array
     * @throws \Exception
     */
    public   function shenhe(string $order_id,int $order_status,$remarks){
        if(empty($order_id)) return error('请选择订单');
        if(!in_array($order_status,[2,7]))return error('参数错误');
        $order=OrderLogic::getOneByOrderId($order_id,['goods_name','user_phone','order_status','my_cou_id','order_id','zm_order_no','order_comefrom']);
        if(empty($order)) return error('该订单不存在');

        $user=Admin::user();
        $user=ob_to_array($user);
        $arr=[
            'admin_phone'=>$user['phone'],
            'admin_name'=>$user['name'],
            'order_id'=>$order_id,
            'create_time'=>date('Y-m-d H:i:s'),
            'oper_action'=>'待审核订单',
            'remarks'=>$remarks
        ];

        // $order_status 订单审核  2通过 7拒绝
        if ($order_status == 2) {
            DB::beginTransaction();
            try{
                $res= OrderModel::where("order_id",$order_id)->update(['order_status'=>'2']);
                if(empty($res)) throw new \Exception('审核失败');
                $res=OrderOperatorModel::insert($arr);
                if(empty($res)) throw new \Exception('审核失败');
                $Sms=orderCheckSmsCode($order["user_phone"],$order["goods_name"],2);

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                return error($e->getMessage());
            }
            return success('审核成功');
        }


        if($order_status==7){
            if (!in_array($order["order_status"], [0,1,2])) return error('该订单不允许取消');
            $data=[
                'order_status'=>7,
                'order_remarks'=>'后台主动拒绝:'.$arr["remarks"]
            ];

            if ($order["zm_order_no"])
            {
                if ($order["order_comefrom"] == 'H5_ZFB')
                {
                    $ZmXy=new ZmXyController();
                    $res=$orderRentCancel=$ZmXy->orderRentCancel($order['zm_order_no']);
                    if (!$res)return error('信用借还订单拒绝失败');
                }

                if($order["order_comefrom"] == 'XCX_ZFB')
                {
                    $data["describe"]="等待异步结果";
                    $OutApi= new ZhimaController();
                    $res=$orderRentCancel=$OutApi->credit_pay('CANCEL',$order['order_id'],$order['zm_order_no']);
                    if (!$res) return error('信用借还订单拒绝失败');
                }

                if ($order["order_comefrom"] == 'H5_JD')
                {
                    $JdDk = new JdDkController();
                    $res=$JdDk->contractCancel($order['order_id'],$order['zm_order_no']);
                    if (!$res) return error('信用借还订单拒绝失败');
                }
            }
            //如果有使用优惠券
            if (($order["my_cou_id"]))
            {
                $res=OrderLogic::cancelCoupon($order_id,$order["my_cou_id"]);
                if (!$res) return error('更改优惠券状态失败');
            }


            DB::beginTransaction();
            try{
                $res= OrderModel::where("order_id",$order_id)->update($data);
                if(empty($res)) throw new \Exception('拒绝失败');
                $res= OrderOperatorModel::insert($arr);
                if(empty($res)) throw new \Exception('拒绝失败');
                $Sms=orderCheckSmsCode($order["user_phone"],$order["goods_name"],7);

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                return error($e->getMessage());
            }
            die(json_success('拒绝成功'));
        }
    }

    /** 订单出库
     * @param $order_id
     * @param $group_id
     * @return array
     * @throws \Exception
     */
    public function orderConfirmDelivery($order_id,$group_id){
        $order_id=trim(request("order_id"));
        $group_id=(int)request("group_id");
        $order=OrderLogic::getOneByOrderId($order_id);
        if(empty($order)) return error('该订单不存在');
        if($order['order_status']!=2) return error('该订单状态无法出库');


        if($group_id>0){
            $num= OrderGroupModel::where('id',$group_id)->count();
            if($num==0)return error('该分组不存在');
            $num= OrderGroupBinModel::where([['group_id',$group_id],['order_id',$order_id]])->count();
            if($num==0){
                 OrderGroupBinModel::insert(['order_id'=>$order_id,'group_id'=>$group_id]);
            }
        }


        $user=Admin::user();
        $user=ob_to_array($user);
        $arr=[
            'admin_phone'=>$user['phone'],
            'admin_name'=>$user['name'],
            'order_id'=>$order_id,
            'create_time'=>date('Y-m-d H:i:s'),
            'oper_action'=>'待发货订单',
            'remarks'=>'订单出库'
        ];

        $data=[
            'order_status'=>3,
            'order_entry_time'=>OrderLogic::order_sxsj(),
            'order_delivery_time'=>date('Y-m-d H:i:s'),
        ];
        $trade_status=LogNotifyAlipayModel::where("order_stages_id",$order['zm_order_no'])->value("trade_status");

        //如果订单是全款购买
        if($order["order_type"] == 2 && $trade_status != 'TRADE_SUCCESS') return error('该订单没有付款');

        //详细租期数据检查
        if($order['goods_lease_id']>0 && $order['goods_lease_term_data']){
            $goods_lease_term= json_decode($order['goods_lease_term_data'],true);
            if(empty($goods_lease_term) || !is_array($goods_lease_term)) return error('订单数据有误');
            $total_price=0;
            $ps=1;
            foreach ($goods_lease_term as $k=>$v){
                if(!isset($v['price']) || !isset($v['day_num']) || !isset($v['goods_lease_id'])){
                    $ps=0;break;
                }
                if($v['goods_lease_id']!=$order['goods_lease_id']){
                    $ps=0;break;
                }
                $total_price+=$v['price'];
            }
            if($ps!=1) return error('租期数据有误');


            $total_price=number_deal($total_price,2);

            if($order['order_gross_rent']<$total_price || ($order['order_gross_rent']-$total_price)>0.5) return error('订单租金有误');
            if($order['order_tenancy_term']!=count($goods_lease_term)) return error('订单租期数有误');
        }

        //如果是分期付款
        if($order["order_type"] == 1)
        {
            DB::beginTransaction();
            try{
                $res= OrderModel::where("order_id",$order_id)->update($data);
                if(empty($res)) throw new \Exception('出库失败');
                $res= OrderOperatorModel::insert($arr);
                if(empty($res)) throw new \Exception('出库失败');

                /****插入分期表****/
                $arr_stages=[];
                for ($i=1; $i <= $order["order_tenancy_term"]; $i++)
                {
                    $order_stages=[];
                    $order_stages['id']=build_order_no().$i;
                    $order_stages["order_id"]=$order_id;
                    $order_stages["user_phone"]=$order["user_phone"];//手机号
                    $order_stages["tenancy_term"]=$order["order_tenancy_term"];//租期
                    $order_stages["current_tenancy_term"]=$i;//当前期数 默认为1
                    $order_stages["monthly_rent"]=$order["order_monthly_rent"];//月租
                    $order_stages["paid_monthly_rent"]=0;//已付月租金额
                    $order_stages["rent_days"]=30; //每期天数
                    $order_stages["goods_installation_charge"]=0;//安装包金额
                    $order_stages["order_goods_insurance"]=0;//意外保障费用
                    $order_stages["cou_onle_id"]=0;
                    $order_stages["cou_credit_amount"]=0;
                    $order_stages["order_stages_pay"]=1;
                    if($order['goods_lease_id']>0){
                        $order_stages["monthly_rent"] = $goods_lease_term[$i-1]['price'];
                        $order_stages["rent_days"] = $goods_lease_term[$i-1]['day_num'];
                    }

                    if ($i == 1)
                    {
                        $order_stages["goods_installation_charge"]=$order["order_installation_charge"];//安装包金额
                        $order_stages["order_goods_insurance"]=$order["order_goods_insurance"];//意外保障费用
                        //如果有使用优惠券
                        if (!empty($order["my_cou_id"]))
                        {
                            $order_stages["cou_onle_id"]=$order["my_cou_id"];
                            $coupon=CouCouponModel::join("coupon as b",'cou_coupon.cou_id','=','b.cou_id')->where('cou_coupon.id',$order['my_cou_id'])
                                ->select("b.is_breaks","b.cou_price")->first();
                            if(empty($coupon)) continue;
                            $coupon=ob_to_array($coupon);
                            //该券是减免还是折扣券  1 减免券   2 打折券
                            if ($coupon["is_breaks"]==1)
                            {
                                $order_stages["cou_credit_amount"]=$coupon["cou_price"];
                            }else{
                                //  优惠券减免金额=月租-月租*（折数/10）
                                //$order_stages["cou_credit_amount"]=cutOut($order["order_monthly_rent"]-$order["order_monthly_rent"]*($coupon["cou_price"]/10),2);
                                //优惠券减免金额=月租*（折数/10）
                                $order_stages["cou_credit_amount"]=number_deal($order["order_monthly_rent"]*($coupon["cou_price"]/10),2);
                            }
                        }
                    }
                    //risk_status 1全部  2部分
                    if($order["risk_status"] == 2 && $order["order_comefrom"] =='H5_ZFB_HB')
                    {
                        if($i > $order["order_tenancy_term"]-3)
                        {
                            $order_stages["order_stages_pay"]=1;// 账单支付方式 1代扣  2主动还款  3两种都可以
                        }else{
                            $order_stages["order_stages_pay"]=2;
                        }
                    }

                    if(strpos($order["order_comefrom"],'XCX_ZFB') !==false)
                    {
                        $order_stages["order_stages_pay"]=1;
                    }

                    if($order["order_comefrom"] == "H5_JD")
                    {
                        $order_stages["order_stages_pay"]=3;
                    }
                    //应付金额 =  月租 - 优惠券减免金额 + 安装包金额 + 意外保障费
                    $order_stages["total_pay"]=number_deal($order_stages["monthly_rent"]-$order_stages["cou_credit_amount"]+$order_stages["goods_installation_charge"]+$order_stages["order_goods_insurance"],2);

                    $order_stages["fq_status"]=1;//状态：1待还款 2已还款  3逾期中 4异常退货
                    $order_stages["create_time"]=date("Y-m-d H:i:s");
                    $order_stages["repayment_time"]=OrderLogic::hk_date($data["order_delivery_time"],$i,$order_stages['rent_days']);//每月还款时间
                    $arr_stages[]=$order_stages;
                }

                $res = OrderStagesModel::insert($arr_stages);
                if(empty($res)) throw new \Exception('出库失败');
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                return error($e->getMessage());
            }
            //短信通知 todo
            $duanxin=MsgLogic::getSmsCode('chuku',$order["user_phone"],'kong','kong',$order["goods_name"]);
            return success('出库成功');
        }

        if($order["order_type"] == 2 && $trade_status == 'TRADE_SUCCESS'){
            $res= OrderModel::where("order_id",$order_id)->update($data);
            if($res) return success('出库成功');
            return error('出库失败');
        }

        return error('出库失败');
    }



    /** 填写快递单号
     * @param $order_id
     * @param $exp_number
     * @param $express
     * @param $remarks
     * @throws \Exception
     */
    public  function seExptNumber($order_id,$exp_number,$express,$remarks){
        $fields_ar=["order_type","risk_status","my_cou_id","order_installation_charge","order_goods_insurance","user_phone","goods_id","user_phone","order_tenancy_term","order_monthly_rent","order_gross_rent","order_comefrom","zm_order_no","goods_name",'order_delivery_time','order_status'];
        $order=OrderLogic::getOneByOrderId($order_id,$fields_ar);
        if(empty($order)) return error('该订单不存在');
        if(!in_array($order['order_status'],[3,4,5,8])) return error('该订单状态不能填写快递订单号');

        $user=Admin::user();
        $user=ob_to_array($user);
        $arr=[
            'admin_phone'=>$user['phone'],
            'admin_name'=>$user['name'],
            'order_id'=>$order_id,
            'create_time'=>date('Y-m-d H:i:s'),
            'oper_action'=>'补填快递订单号',
            'remarks'=>$remarks
        ];
        $data=[
            'express'=>$express,
            'exp_number'=>$exp_number
        ];

        try{
            DB::beginTransaction();
            $res= OrderModel::where("order_id",$order_id)->update($data);
            if(empty($res)) throw new \Exception('快递订单号填写失败');
            $res= OrderOperatorModel::insert($arr);
            if(empty($res)) throw new \Exception('快递订单号填写失败');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }
        return success('填写成功');
    }

    /** 确认发货
     * @param $order_id
     * @param $exp_number
     * @param $express
     * @param $remarks
     * @return array
     * @throws \Exception
     */
    public function fahuo($order_id,$exp_number,$express,$remarks){
        $fields_ar=["order_type","risk_status","my_cou_id","order_installation_charge","order_goods_insurance","user_phone","goods_id","user_phone","order_tenancy_term","order_monthly_rent","order_gross_rent","order_comefrom","zm_order_no","goods_name",'order_delivery_time','order_status'];
        $order=OrderLogic::getOneByOrderId($order_id,$fields_ar);
        if(empty($order)) return error('该订单不存在');

        if($order['order_status'] !=3) return error('该订单状态不能发货');
        if(empty($order['order_delivery_time'])) return error('该订单必须出库才能发货');



        $user=Admin::user();
        $user=ob_to_array($user);
        $arr=[
            'admin_phone'=>$user['phone'],
            'admin_name'=>$user['name'],
            'order_id'=>$order_id,
            'create_time'=>date('Y-m-d H:i:s'),
            'oper_action'=>'已出库订单',
            'remarks'=>$remarks
        ];
        $data=[
            'express'=>$express,
            'exp_number'=>$exp_number
        ];

        /*H5 信用借还*/
        if ($order["order_comefrom"] == 'H5_ZFB')
        {
            $order_no=$order["zm_order_no"]; //信用借还内部单号
            $borrow_time=OrderLogic::order_sxsj();//开始时间(发货时间加5天)
            $expiry_time=OrderLogic::order_sxsj($order["order_tenancy_term"]);//  发货时间加5天后加上分期月份

           /* $ZmXy=new ZmXyController();
            $orderRentModify=$ZmXy->orderRentModify($order_no,$borrow_time,$expiry_time);
            if(!$orderRentModify) return error('生成信用借失败！');


            $Signature=new SignatureController();
            $Signature_res=$Signature->SeriesContract($order_id,$exp_number);
            if(!$Signature_res) return error('生成上上签合同号失败！');*/
        }
        if ($order["order_comefrom"] == 'H5_JD' || $order["order_comefrom"] == 'XCX_ZFB')
        {

           /* $Signature=new SignatureController();
            $Signature_res=$Signature->SeriesContract($order_id,$exp_number);
            if(!$Signature_res) return error('生成上上签合同号失败！');*/
        }

        try{
            DB::beginTransaction();
            $res= OrderModel::where("order_id",$order_id)->update($data);
            if(empty($res)) throw new \Exception('发货失败');
            $res=OrderOperatorModel::insert($arr);
            if(empty($res)) throw new \Exception('发货失败');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();

            return error($e->getMessage());
        }
        $duanxin=MsgLogic::getSmsCode($order["order_comefrom"],$order["user_phone"],$express,$exp_number,$order["goods_name"]);

        return success('发货成功');
    }

    /**通过订单id得到风控结果
     * @param string $order_id
     * @return array
     */
    public  function xxhf(string $order_id){
        if(empty($order_id)) return error('缺少参数');
        $order=OrderLogic::getOneByOrderId($order_id,["user_phone","user_id_number","order_gross_rent"]);
        if(empty($order)) return error('该订单不存在');
        if(empty($order['user_phone']))return error('该订单缺少手机号');
        $user= UserModel::where("phone",$order['user_phone'])->select("zm_user_id")->first();
        if(empty($user))return error('订单用户不存在');
        $user=ob_to_array($user);

        $da=[
            'user_phone'=>$order['user_phone'],
            'user_id_number'=>$order['user_id_number'],
            'order_gross_rent'=>$order['order_gross_rent'],
            'zm_user_id'=>$user['zm_user_id']
        ];
        $data=XxhfLogic::getXxhf($da);
        if(isset($data['status']) && $data['status']==0) return $data;

        $log_data=[
            'order_id'=>$order_id,
            'phone'=>$order['user_phone']??'',
            'idcard'=>$order['user_id_number']??'',
            'amount'=>$order['order_gross_rent'],
            'zm_user_id'=>$user['zm_user_id']??'',
            'time'=>date('Y-m-d H:i:s')
        ];
        $log_data['json_res']= $data['data']['json_res'];
        $log_data['res']= $data['data']['res'];
        $log_num= LogXxhfModel::where("order_id",$order_id)->count();
        if($log_num>0){
            LogXxhfModel::where("order_id",$order_id)->update($log_data);
        }else{
            LogXxhfModel::insert($log_data);
        }
        return $data;
    }

    /** 移除分组
     * @param array $orderIds
     * @param int $group_id
     * @return array
     */
    public   function removeGroup(array $orderIds,int $group_id){
        if(empty($orderIds) || !is_array($orderIds)) die(json_error('请选择订单'));

        $model= OrderGroupBinModel::where('order_id',$orderIds);
        if($group_id>0) $model->where('group_id',$group_id);
        $res=$model->delete();
        if(!$res) return error('解除失败');
        return success('解除成功');
    }

    /** 分组
     * @param array $para
     * @return array
     */
    public   function setGroup(array $para){
        $group_id= isset($para['group_id'])?$para['group_id']:0;
        $order_id=isset($para['order_id'])?$para['order_id']:[];

        if(empty($group_id)) return error('请选择分组');
        if(empty($order_id) || !is_array($order_id)) return error('请选择订单');

        $num= OrderGroupModel::where('id',$group_id)->count();
        if($num==0) return error('该分组不存在');

        $order= OrderModel::whereIn('order_id',$order_id)->pluck('order_id');
        $order=ob_to_array($order);
        if(empty($order))  return error('参数有误');
        $seted_order= OrderGroupBinModel::whereIn('order_id',$order)->where('group_id',$group_id)->pluck('order_id');
        $seted_order=ob_to_array($seted_order);
        $order=array_diff($order,$seted_order);
        if(empty($order))  return error('订单已在该组中');
        $data=[];
        foreach($order as $v){
            $data[]=['order_id'=>$v,'group_id'=>$group_id];
        }
        $res=OrderGroupBinModel::insert($data);
        if(!$res)  return error('设置失败');
        return success('设置成功');
    }

    public   function exportOrderExcel(array $para){
        $xxhf= isset($para['xxhf'])?$para['xxhf']:0;
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_type=isset($para['order_type'])?$para['order_type']:0;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';

        $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status!=-1 ){
            $searchWhere[] = ['order_status',$order_status];
            if($order_status==3){
                $searchWhere[] = ['express','<>',''];
                $searchWhere[] = ['exp_number','<>',''];
            }
            if($order_status==33){
                $searchWhere[] = ['express',''];
                $searchWhere[] = ['exp_number',''];
                $searchWhere[] = ['order_delivery_time','<>',''];
            }

        }


        if($order_type){
            $searchWhere[] = ['order_type',$order_type];
        }
        if($order_comefrom){
            $searchWhere[] = ['order_comefrom',$order_comefrom];
        }
        if ($order_id) {
            $searchWhere[] = ['order_id', 'like', $order_id . '%'];
        }
        if ($goods_name) {
            $searchWhere[] = ['goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $searchWhere[] = ['user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $searchWhere[] = ['user_name', 'like', $user_name . '%'];
        }
        if ($start_time) {
            $whereRaw.="`order_create_time` > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="`order_create_time` <  ? ";
            $whereCol[]=$end_time;
        }



        $model = OrderModel::where($searchWhere);
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);
        $model->limit(100);
        $data=$model->get();
        $data=ob_to_array($data);



        $order_ids=$data?array_column($data,'order_id'):[0];
        $xxhf_log=LogXxhfLogic::getResByOrderIds($order_ids);
        $channel=ChannelLogic::pluck('cha_describe','cha_name');
        $url=config('sys.img_url').'/';
        $order_status=config('sys.order_status');
        foreach($data as $k=>$v){
            $data[$k]["goods_order_thumbnail"]=$url.trim($v['goods_order_thumbnail'],'/');
            $data[$k]["order_address"]=$v["user_province"].$v["user_address"];
            $data[$k]["cha_describe"]=$channel[$v['order_comefrom']]??'';//订单来源
            $data[$k]['log_xxhf']=$xxhf_log[$v['order_id']]??'';
            $data[$k]['order_status']=$order_status[$v['order_status']]??'';
            if($order_status==33){
                $data['data'][$k]['order_status']='已出库';
            }
        }


        $csv = new CsvUtil();
        $filename = '订单列表' . date('YmdHis') . '.csv';
        $csv->csvHeader($filename);
        $head = ['订单状态','订单来源','订单号','商品名称','商品规格','信用分','客户名称','客户手机号','身份证号码','收货地址','下单时间','发货时间','总期数','剩余还款期数','剩余还款金额','快递公司','快递单号','银行卡卡号'];
        if($xxhf==1)$head[]="先享后付风控";

        $csv->outputData($head);
        $limit = 100000;     //刷新缓存限制，避免php缓存过大
        $cnt   = 0;         //用于计算缓存数量
        $size  = 20000;

        $user_phones=array_column($data,'user_phone')?:[0];
        if($xxhf==1){
            $user_phones=UserModel::whereIn('phone',$user_phones)->pluck('zm_user_id','phone');
            $user_phones=ob_to_array($user_phones);
        }
        $bankCard=UserModel::whereIn('phone',$user_phones)->pluck("bankCard",'phone');
        $bankCard=ob_to_array($bankCard);

        foreach($data as $item){
            if (!strtotime($item['order_delivery_time']))
            {
                $item['order_delivery_time'] = 0;
            }
            $item['bankCard']=isset($bankCard[$item['user_phone']])?$bankCard[$item['user_phone']]:'';

            if($xxhf==1){
                $zm_user_id=!empty($user_phones[$item['user_phone']])?$user_phones[$item['user_phone']]:'null';
                $da=[
                    'amount'=>$item['order_rema_amount_pay'],
                    'zm_user_id'=>$zm_user_id,
                    'phone'=>$item['user_phone'],
                    'idcard'=>$item['user_id_number']
                ];
                $xxhf_res='';
                try{
                    $xxhf_res=$this->get_xxhf($da);
                    $xxhf_res=$xxhf_res?$xxhf_res:'检查失败';
                }catch (\Exception $e){
                    $xxhf_res=$e->getMessage();
                }
            }


            $_data=[
                $item['order_status'],
                $item['cha_describe'],
                "\t".$item['order_id'],
                $item['goods_name'],
                $item['goods_order_attr'],
                $item['zm_credit_score'],
                $item['user_name'],
                "\t".$item['user_phone'],
                "\t".$item['user_id_number'],
                $item['order_address'],
                $item['order_create_time'],
                $item['order_delivery_time'],
                $item['order_tenancy_term'],
                $item['order_repay_period'],
                $item['order_rema_amount_pay'],
                $item['express'],
                "\t".$item['exp_number'],
                "\t".$item['bankCard'],
            ];
            if($xxhf==1)$_data[]=$xxhf_res;
            $cnt++;
            if ($limit == $cnt) {
                //刷新一下输出buffer，防止由于数据过多造成问题
                $csv->csvFlush($cnt);
            }
            $csv->outputData($_data);
        }
        unset($items,$paySource,$channels);
        $csv->closeFile();  //每生成一个文件关闭
        exit;
    }

    /** 资金清单
     * @param array $para
     * @return array
     */
    public function capitalList(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_type=isset($para['order_type'])?$para['order_type']:0;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';
        $daochu=isset($para['daochu'])?$para['daochu']:0;


        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status!=-1 ){
            $searchWhere[] = ['order_status',$order_status];
            $where['order_status']=$order_status;
        }
        if($order_type){
            $where['order_type'] = $order_type;
            $searchWhere[] = ['order_type',$order_type];
        }
        if($order_comefrom){
            $where['order_comefrom'] = $order_comefrom;
            $searchWhere[] = ['order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['order_id', 'like', $order_id . '%'];
        }
        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $where['user_phone'] = $user_phone;
            $searchWhere[] = ['user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $where['user_name'] = $user_name;
            $searchWhere[] = ['user_name', 'like', $user_name . '%'];
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="`order_create_time` > ? ";
            $whereCol[]=$start_time;
        }
        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="`order_create_time` <  ? ";
            $whereCol[]=$end_time;
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }



        $model = OrderModel::where($searchWhere)->orderBy('order_id','desc');
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);
        if($daochu==1)$per_page=100;
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $order_ids=$data['data']?array_column($data['data'],'order_id'):[0];
        //首期账单
        $first_stages=OrderStagesModel::select('monthly_rent','repayment_time','order_id')->whereIn('order_id',$order_ids)
            ->where('current_tenancy_term',1)->get();
        $first_stages=ob_to_array($first_stages);
        $first_stages_ar=[];
        foreach($first_stages as $v){
            $first_stages_ar[$v['order_id']]=$v;
        }

        $order_id_string = "'" . join("','", $order_ids) . "'";
        $sql="select a.order_id,a.current_tenancy_term,a.alipay_fund_order_no,a.repayment_time from order_stages as a
join (select order_id, GROUP_CONCAT(current_tenancy_term order by current_tenancy_term desc ) as ids  from order_stages where  order_id in (".$order_id_string.") GROUP BY order_id ) as b 
ON a.order_id=b.order_id
where a.fq_status=2 and  a.order_id in (".$order_id_string.") and FIND_IN_SET(a.current_tenancy_term,b.ids) BETWEEN 1 and 1   ORDER BY order_id desc,current_tenancy_term desc";
        $newest_finish_stages=DB::select($sql);
        $newest_finish_stages=ob_to_array($newest_finish_stages);
        $newest_finish_stages_ar=[];
        foreach($newest_finish_stages as $v){
            $newest_finish_stages_ar[$v['order_id']]=$v;
        }

        $channel=ChannelLogic::pluck('cha_describe','cha_name');
        $order_status=config('sys.order_status');
        $order_type=config('sys.order_type');
        foreach($data['data'] as $k=>$v){
            $data['data'][$k]["order_address"]=$v["user_province"].$v["user_address"];
            $data['data'][$k]["order_comefrom"]=$channel[$v['order_comefrom']]??'';//订单来源
            $data['data'][$k]['order_status']=$order_status[$v['order_status']]??'';
            $data['data'][$k]['order_type']=$order_type[$v['order_type']]??'';
            $data['data'][$k]['first_monthly_rent']=$first_stages_ar[$v['order_id']]['monthly_rent']??'';
            $data['data'][$k]['first_repayment_time']=$first_stages_ar[$v['order_id']]['repayment_time']??'';

            $data['data'][$k]['newest_alipay_fund_order_no']=$newest_finish_stages_ar[$v['order_id']]['alipay_fund_order_no']??'';
            $data['data'][$k]['newest_current_tenancy_term']=$newest_finish_stages_ar[$v['order_id']]['current_tenancy_term']??'';
            $data['data'][$k]['newest_repayment_time']=$newest_finish_stages_ar[$v['order_id']]['repayment_time']??'';
        }
        if($daochu==1){
            set_time_limit(0);
            $csv = new CsvUtil();
            $filename = '资金方清单' . date('YmdHis') . '.csv';
            // 输出Excel文件头
            $csv->csvHeader($filename);
            $head = ['订单状态', '订单类型','订单来源', '订单号', '商品名称', '商品规格', '信用分', '客户名称', '客户手机号', '身份证号码', '收货地址', '下单时间','订单总金额', '总期数', '剩余还款期数', '剩余还款金额', '快递公司', '快递单号', '首期账单日',  '当期账单金额', '支付宝对账单号', '支付宝对账期数', '最近一期已完成的账单日'];
            //转换编码
            $csv->outputData($head);
            $limit = 100000;     //刷新缓存限制，避免php缓存过大
            $cnt = 0;         //用于计算缓存数量
            $size = 20000;


            foreach ($data['data'] as $item) {
                $_data = [
                    $item['order_status'],
                    $item['order_type'],
                    $item['order_comefrom'],
                    "\t" . $item['order_id'],
                    $item['goods_name'],
                    $item['goods_order_attr'],
                    $item['zm_credit_score'],
                    $item['user_name'],
                    $item['user_phone'],
                    "\t" . $item['user_id_number'],
                    $item['order_address'],
                    $item['order_create_time'],
                    $item['order_gross_rent'],
                    $item['order_tenancy_term'],
                    $item['order_repay_period'],
                    $item['order_rema_amount_pay'],
                    $item['express'],
                    "\t" . $item['exp_number'],
                    $item['first_repayment_time'],

                    $item['first_monthly_rent'],
                    "\t" . $item['newest_alipay_fund_order_no'],
                    $item['newest_current_tenancy_term'],
                    $item['newest_repayment_time'],
                ];

                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    $csv->csvFlush($cnt);
                }
                $csv->outputData($_data);
            }
            unset($items, $paySource, $channels);
            $csv->closeFile();  //每生成一个文件关闭
            exit;
        }



        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url='?';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url,
            'channel'=>$channel,
            'excel_url'=>$excel_url,
        ];
        return $arr;


    }








}
